package org.jeecgframework.web.service.impl;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.CbsReturnEquipmentServiceI;
import org.jeecgframework.web.system.pojo.base.CbsHandleLogEntity;
import org.jeecgframework.web.system.pojo.base.CbsReturnEquipmentDetailEntity;
import org.jeecgframework.web.system.pojo.base.CbsReturnEquipmentEntity;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.io.Serializable;

@Service("cbsReturnEquipmentService")
@Transactional
public class CbsReturnEquipmentServiceImpl extends CommonServiceImpl implements CbsReturnEquipmentServiceI {

	@Autowired
	private SystemService systemService;

 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((CbsReturnEquipmentEntity)entity);
 	}

 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
 		this.doAddSql((CbsReturnEquipmentEntity)entity);
 		return t;
 	}

 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
 		this.doUpdateSql((CbsReturnEquipmentEntity)entity);
 	}

 	/**
	 * 默认按钮-sql增强-新增操作
	 * @param id
	 * @return
	 */
 	public boolean doAddSql(CbsReturnEquipmentEntity t){
	 	return true;
 	}

 	public String getReturnCode(){
 		String code="";
		//组装返件单号FH+YYYYMMDD+001(增长)
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("YYYYMMdd");
		String time = format.format(date);
		StringBuffer buffer = new StringBuffer();
		buffer.append("FJ");
		buffer.append(time);
		List<Object[]> returnEquipmentList = super.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
		if (returnEquipmentList.size() == 0) {
			buffer.append("001");
			String s = buffer.toString();
			code=s;
		} else {
			String o = (String) returnEquipmentList.get(0)[1];
			String s = o.substring(10, 13);
			int l = Integer.parseInt(s);
			l++;
			if (l <= 9) {
				buffer.append("00" + l);
			} else if (l >= 10 && l < 100) {
				buffer.append("0" + l);
			} else {
				buffer.append("" + l);
			}
			String string = buffer.toString();
			code=string;
		}
 		return code;
	}


	public String getUuid(){
 	    return UUID.randomUUID().toString().replaceAll("-", "");
    }

 	public void updateLogistics(String id,String logistics){
		TSUser user= ResourceUtil.getSessionUserName();
		CbsReturnEquipmentEntity cbsReturnEquipmentEntity = super.get(CbsReturnEquipmentEntity.class, id);
		if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
			if(StringUtil.isNotEmpty(cbsReturnEquipmentEntity.getLogistics()) && !cbsReturnEquipmentEntity.getLogistics().equals(logistics)){
				//如果返件状态为取件中的时候修改物流，原返件单变为已取消，重新生成一个新物流的返件任务，状态为返件中
				if(cbsReturnEquipmentEntity.getStatus().equals("3")){
					CbsReturnEquipmentEntity cbsReturnEquipmentEntityNew=new CbsReturnEquipmentEntity();
					// 将旧返件单的数据复制给新的返件单
					BeanUtils.copyProperties(cbsReturnEquipmentEntity, cbsReturnEquipmentEntityNew);
					cbsReturnEquipmentEntityNew.setId(getUuid());
					cbsReturnEquipmentEntityNew.setCreateBy(user.getUserName());
					cbsReturnEquipmentEntityNew.setNoticeReturnTime(new Date());
					cbsReturnEquipmentEntityNew.setStatus("2");
					cbsReturnEquipmentEntityNew.setCreateDate(new Date());
					cbsReturnEquipmentEntityNew.setCode(getReturnCode());
					cbsReturnEquipmentEntityNew.setCreateName(user.getRealName());
					super.save(cbsReturnEquipmentEntityNew);

					List<CbsReturnEquipmentDetailEntity> returnDetailList=super.findHql("from CbsReturnEquipmentDetailEntity where returnEquipmentId.id='"+cbsReturnEquipmentEntity.getId()+"'");
                    if(returnDetailList!=null && returnDetailList.size()>0){
                        for(CbsReturnEquipmentDetailEntity returnDetail:returnDetailList){
                            if(StringUtil.isNotEmpty(returnDetail)){
                                CbsReturnEquipmentDetailEntity returnDetailNew=new CbsReturnEquipmentDetailEntity();
                                BeanUtils.copyProperties(returnDetail, returnDetailNew);
                                returnDetailNew.setId(getUuid());
                                returnDetailNew.setReturnEquipmentId(cbsReturnEquipmentEntityNew);
                                super.save(returnDetailNew);
                            }

                        }
                    }
					//创建返件日志
					CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
					cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntityNew.getId());
					cbsHandleLogEntity.setLogType(4);
					cbsHandleLogEntity.setDescription("创建返件申请单");
					cbsHandleLogEntity.setCreateName(user.getRealName());
					cbsHandleLogEntity.setCreateBy(user.getUserName());
					super.saveOrUpdate(cbsHandleLogEntity);

					cbsReturnEquipmentEntity.setStatus("5");
					super.saveOrUpdate(cbsReturnEquipmentEntity);
					//创建返件取消日志
					CbsHandleLogEntity cbsHandleLogEntity1 = new CbsHandleLogEntity();
					cbsHandleLogEntity1.setBusinessId(cbsReturnEquipmentEntity.getId());
					cbsHandleLogEntity1.setLogType(4);
					cbsHandleLogEntity1.setDescription("取消返件");
					cbsHandleLogEntity1.setCreateName(user.getRealName());
					cbsHandleLogEntity1.setCreateBy(user.getUserName());
					super.saveOrUpdate(cbsHandleLogEntity1);

				}
				if(cbsReturnEquipmentEntity.getStatus().equals("1") || cbsReturnEquipmentEntity.getStatus().equals("2")){
					cbsReturnEquipmentEntity.setLogistics(logistics);
					super.saveOrUpdate(cbsReturnEquipmentEntity);
				}
			}
		}

 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @param id
	 * @return
	 */
 	public boolean doUpdateSql(CbsReturnEquipmentEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @param id
	 * @return
	 */
 	public boolean doDelSql(CbsReturnEquipmentEntity t){
	 	return true;
 	}

 	/**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,CbsReturnEquipmentEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{code}",String.valueOf(t.getCode()));
 		sql  = sql.replace("#{sr_code}",String.valueOf(t.getSrCode()));
 		sql  = sql.replace("#{so_code}",String.valueOf(t.getSoCode()));
 		sql  = sql.replace("#{cr_code}",String.valueOf(t.getCrCode()));
 		sql  = sql.replace("#{deliver_code}",String.valueOf(t.getDeliverCode()));
 		sql  = sql.replace("#{equipment_apply_id}",String.valueOf(t.getEquipmentApplyId()));

 		sql  = sql.replace("#{status}",String.valueOf(t.getStatus()));
 		sql  = sql.replace("#{candel_des}",String.valueOf(t.getCandelDes()));
 		sql  = sql.replace("#{pickup_time}",String.valueOf(t.getPickupTime()));
 		sql  = sql.replace("#{backwarehouse_time}",String.valueOf(t.getBackwarehouseTime()));
 		sql  = sql.replace("#{logistics_code}",String.valueOf(t.getLogisticsCode()));
 		sql  = sql.replace("#{logistics_memo}",String.valueOf(t.getLogisticsMemo()));
 		sql  = sql.replace("#{unqualified}",String.valueOf(t.getUnqualified()));
 		sql  = sql.replace("#{unqualified_memo}",String.valueOf(t.getUnqualifiedMemo()));
 		sql  = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
 		sql  = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
 		sql  = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
 		sql  = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
 		sql  = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
 		sql  = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}



	/*
	 * csa导出EXCEl
	 * */
	public void exportReturnList(HttpServletRequest request, HttpServletResponse response) {

		OutputStream out = null;
		try {
			String fileName = "返件信息.xlsx";
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename=" + (new String(fileName.getBytes("gb2312"), "ISO8859-1")));
			out = response.getOutputStream();
			String[] ReturnIdsArr = oConvertUtils.getString(request.getParameter("returnIds")).split(",");
			StringBuffer sql = new StringBuffer();
			String sql1="SELECT\n" +
					"        e.id AS id,\n" +
					"        IFNULL(e.`code`,'') AS CODE,\n" +
					"        CASE WHEN e. STATUS = '1' THEN '未返件' " +
					"         WHEN e. STATUS = '2' THEN '物流待处理' " +
					"         WHEN e. STATUS = '3' THEN '取件中' " +
					"         WHEN e. STATUS = '4' THEN '已入库' " +
					"         WHEN e. STATUS = '5' THEN '取消返件' " +
					"         END AS status,"+
					"        IFNULL(e.so_code,'') AS so,\n" +
					"        IFNULL(e.cinema_name,'') AS cinemaName,\n" +
					"        ifnull(ts1.territoryname, '') AS shengName,\n" +
					"        ifnull(ts2.territoryname, '') AS shiName,\n" +
					"        IFNULL(d.type_des,'') AS typedes,\n" +
					"        IFNULL(d.item,'') AS item,\n" +
					"        IFNULL(d.item_total,'') AS itemtotal,\n" +
					"        IFNULL(e.logistics_code,'') AS logisticscode,\n" +
					"        IFNULL(e.logistics,'') AS logistics,\n" +
					"        IFNULL(e.create_date,'') AS createDate,\n" +
					"        CASE\n" +
					"        WHEN e. STATUS IN (1, 5) THEN\n" +
					"        '--'\n" +
					"        WHEN e. STATUS = '4' THEN\n" +
					"        FORMAT(\n" +
					"        TIMESTAMPDIFF(\n" +
					"        SECOND,\n" +
					"        e.noticeReturn_time,\n" +
					"        e.inwarehouse_time\n" +
					"        ) / 60 / 60,\n" +
					"        2\n" +
					"        )\n" +
					"        WHEN e. STATUS IN (2, 3) THEN\n" +
					"        FORMAT(\n" +
					"        TIMESTAMPDIFF(\n" +
					"        SECOND,\n" +
					"        e.noticeReturn_time,\n" +
					"        NOW()\n" +
					"        ) / 60 / 60,\n" +
					"        2\n" +
					"        )\n" +
					"        END AS returnSC,\n" +
					"        IFNULL(e.noticeReturn_time,'') AS noticeReturnTime,\n" +
					"        IFNULL(e.pickup_time,'') AS pickuptime,\n" +
					"        IFNULL(e.inwarehouse_time,'')AS backwarehousetime,\n" +
					"        IFNULL(e.deliver_code,'') AS delivercode,\n" +
					"        IFNULL(a.`record_id`,'') AS codes,\n" +
					"        IFNULL(a.create_name,'') AS applyname,\n" +
					"        IFNULL(depart.shortname,'') AS departname,\n" +
					"        IFNULL(e.cr_code,'') AS cr, \n" +
					"        IFNULL(d.sn ,'') AS re_sn,\n" +
					"        IFNULL(d.equipment_ercode ,'') AS re_qr,\n" +
					"        IFNULL(flr.files,'') AS files,\n" +
					"        IFNULL(back.sn ,'') AS back_sn,\n" +
					"        IFNULL(back.equipment_ercode ,'') AS back_qr\n" +
					"        FROM\n" +
					"        cbs_return_equipment e\n" +
					"        LEFT JOIN cbs_service cbs ON cbs.`code` = e.cr_code\n" +
					"        LEFT JOIN `cbs_return_equipment_detail` d on  d.return_equipment_id = e.id\n" +
					"        LEFT JOIN cbs_back_equipment_detail back on back.return_equipment_detail_id=d.id\n" +
					"        LEFT JOIN (SELECT\n" +
					"        business_child_type,\n" +
					"        IFNULL(GROUP_CONCAT(zy_file_log.old_file_name SEPARATOR '\\\\'),'') AS files \n" +
					"        FROM\n" +
					"        zy_file_log\n" +
					"        WHERE business_type = 'E' \n"+
					"        GROUP BY\n" +
					"        business_child_type \n" +
					"        ) flr ON flr.business_child_type=d.id\n" +
					"        LEFT JOIN CBS_EQUIPMENT_APPLY a ON a.id = e.equipment_apply_id\n" +
					"        LEFT JOIN t_s_base_user bu ON a.create_by = bu.username\n" +
					"        LEFT JOIN t_s_user_org uo ON bu.ID = uo.user_id\n" +
					"        LEFT JOIN t_s_depart depart ON uo.org_id = depart.id\n" +
					"         LEFT JOIN cbs_deliver cd ON cd.`code` = e.deliver_code\n" +
					"        LEFT JOIN t_s_territory ts1 ON ts1.ID = cd.sheng\n" +
					"        LEFT JOIN t_s_territory ts2 ON ts2.ID = cd.shi\n" +
					"        WHERE\n";
			sql.append(sql1);
			sql.append("	e.id IN (\n");
			for (int i = 0; i < ReturnIdsArr.length; i++) {
				if (i == ReturnIdsArr.length - 1) {
					sql.append("'" + ReturnIdsArr[i] + "'");
				} else {
					sql.append("'" + ReturnIdsArr[i] + "',");
				}
			}
			sql.append(") ");

			List<Map<String, Object>> reusltMaps = super.findForJdbc(sql.toString());
			TSUser user = ResourceUtil.getSessionUserName();
			systemService.addLog(user.getRealName()+"导出"+reusltMaps.size()+"发货单记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

            InputStream is = ZyInspectionPlanServiceImpl.class.getClassLoader().getResourceAsStream("jeecg/template/returnList.xlsx");
            XSSFWorkbook xssf = new XSSFWorkbook(is);
            XSSFSheet sheet = xssf.getSheetAt(0);
            int rowNum = 1;
            for (Map<String, Object> dataMap : reusltMaps) {
                XSSFRow row = sheet.createRow(rowNum);
                int cellNum = 0, index = 0;
                for (String key : dataMap.keySet()) {
                    if (index == 0) {
                        index++;
                        continue;
                    }
                    XSSFCell cell = row.createCell(cellNum);
                    cell.setCellValue(dataMap.get(key) != null ? dataMap.get(key).toString() : "");
                    cellNum++;
                }
                rowNum++;
            }
            xssf.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 创建返件日志
     *
     * @param id          返件id
     * @param user        操作用户
     * @param description 描述
     */
    public void createReturnLog(String id, String description, TSUser user) {
        //创建返件取消日志
        CbsHandleLogEntity cbsHandleLogEntity1 = new CbsHandleLogEntity();
        cbsHandleLogEntity1.setBusinessId(id);
        cbsHandleLogEntity1.setLogType(4);
        cbsHandleLogEntity1.setDescription(description);
        cbsHandleLogEntity1.setCreateName(user.getRealName());
        cbsHandleLogEntity1.setCreateBy(user.getUserName());
        super.saveOrUpdate(cbsHandleLogEntity1);
    }
}